//
//  TransportViewModel.swift
//  Automobile
//
//  Created by erkebulan elzhan on 9/1/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit

protocol ViewModelProtocol {
    func updateCities (cities: [City]?)
    func updateSpinner (showSpinner: Bool)
    func didHappenError (error: RequestError)
    func updatePosts()
}

final class TransportViewModel {
    
    var delegate: ViewModelProtocol!
    
    /// Parameters View
    let inputs:[ParametersViewModel] = [
        ParametersViewModel(input:
            Input(type: "markaModel", value: nil, placeholder: "Марка, модель", icon: UIImage(named: "car"))),
        ParametersViewModel(input:
            Input(type: "parameters", value: nil, placeholder: "Параметры", icon: UIImage(named: "settings")))
    ]
    
    /// Cities for filter
    var currentCities: [City]? {
        didSet {
            if self.currentCities != nil {
                self.delegate.updateCities(cities: currentCities)
                self.filter.filterGeneral.region = currentCities
            } else {
                self.delegate.updateCities(cities: nil)
            }
            self.loadPosts()
        }
    }
    
    var filter: Filter! = Filter(filterGeneral: Filter.FilterGeneral(), filterCar: Filter.FilterCar(), filterOptional: Filter.FilterOptional(), filterChecks: Filter.FilterChecks(), carDetailedType: nil) {
        didSet {
            self.loadPosts()
        }
    }
    
    var posts: [Post] = []
    
    // pagination URL
    var nextURL: String?
    
    var marka: String!
    var models: [String: [String]]!
    
    private let backend = Backend()
}

// MARK: - Network

extension TransportViewModel {
    
    public func loadPosts (paginate: Bool = false) {
        let filterManager = FilterManager()
        let request = paginate ? URLRequest(url: URL(string: nextURL!)!) : nil
        
        delegate.updateSpinner(showSpinner: true)
        
        filterManager.getPosts(filter: self.filter, request: request) { (result) in
            self.delegate.updateSpinner(showSpinner: false)
            switch result {
                case .failure(let error):
                    self.delegate.didHappenError(error: error)
                case .success(let posts):
                    self.posts = posts.results
                    self.nextURL = posts.next
                    self.delegate.updatePosts()
            }
        }
    }
    
    public func updateFavorite (isRemove: Bool, index: Int) {
        Backend().addToFavorites(advertID: posts[index].id, isRemove: isRemove) { (isSuccess, errorMessage) in
            if isSuccess {
                self.posts[index].isLiked.toggle()
                self.delegate.updatePosts()
            } else {
                self.delegate.didHappenError(error: .parameter(errorMessage!))
            }
        }
    }
    
    public func callToSeller (index: Int) {
        let post = posts[index]
        
        if let number = post.contactNumbers?.first {
            if let url = URL(string: "tel://\(number)") {
                if #available(iOS 10, *) {
                    UIApplication.shared.open(url, options: [:], completionHandler:nil)
                } else {
                    UIApplication.shared.openURL(url)
                }
            } else {
                delegate.didHappenError(error: .parameter("У нас нет контактного номера данного пользователя"))
            }
        } else {
            delegate.didHappenError(error: .parameter("У нас нет контактного номера данного пользователя"))
        }
    }
}
